#include "Camera.h"

namespace SLG
{
	Camera::Camera(DWORD width, DWORD height)
	{
		m_fovy=D3DX_PI*0.5f;
		m_aspect=(float)width/(float)height;
		m_zn=1.0f;
		m_zf=30.0f;
		Init(width,height);
		m_position=D3DXVECTOR3(0.0f,5.0f,-5.0f);
		m_target=D3DXVECTOR3(0.0f,0.0f,0.0f);
		m_up=D3DXVECTOR3(0.0f,1.0f,0.0f);
		float x=m_target.x-m_position.x;
		float z=m_target.z-m_position.z;
		m_mod=sqrt(x*x+z*z);
		m_unit=D3DXVECTOR2(x/m_mod,z/m_mod);
	}

	Camera::~Camera(void)
	{
	}

	void Camera::ResetCamera(int32 w,int32 h)
	{
		m_position=D3DXVECTOR3(float(w)/2.0f,5.0f,float(h)/2.0f-5.0f);
		m_target=D3DXVECTOR3(float(w)/2.0f,0.0f,float(h)/2.0f);
		m_up=D3DXVECTOR3(0.0f,1.0f,0.0f);
		Update();
	}

	void Camera::Init(DWORD width,DWORD height)
	{
		D3DXMATRIX proj;
		D3DXMatrixPerspectiveFovLH(
			&proj,
			m_fovy,
			m_aspect,
			m_zn,
			m_zf);
		g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &proj);
	}

	void Camera::Update()
	{

		g_pd3dDevice->SetTransform(D3DTS_VIEW, GetViewMatrix());
	}

	void Camera::Shift(bool direction)
	{
		D3DXVECTOR3 move=D3DXVECTOR3(-m_unit.y,0,m_unit.x);
		if(!direction)
		{
			m_position -= move;
			m_target -= move;
		}
		else
		{
			m_position += move;
			m_target += move;
		}
	}
	void Camera::Row(bool direction)
	{
		float x=m_position.x-m_target.x;
		float z=m_position.z-m_target.z;
		float posX=0.0f,posZ=0.0f;
		if(direction)
		{
			posX=x*cos(-CAMERA_ROW)-z*sin(-CAMERA_ROW);
			posZ=x*sin(-CAMERA_ROW)+z*cos(-CAMERA_ROW);
		}
		else
		{
			posX=x*cos(CAMERA_ROW)-z*sin(CAMERA_ROW);
			posZ=x*sin(CAMERA_ROW)+z*cos(CAMERA_ROW);
		}
		posX+=m_target.x;
		posZ+=m_target.z;
		m_position=D3DXVECTOR3(posX,m_position.y,posZ);
		x=m_target.x-m_position.x;
		z=m_target.z-m_position.z;
		m_unit=D3DXVECTOR2(x/m_mod,z/m_mod);
	}

	void Camera::Wolk(bool direction)
	{
		if(direction)
		{
			m_position+=D3DXVECTOR3(m_unit.x,0,m_unit.y);
			m_target+=D3DXVECTOR3(m_unit.x,0,m_unit.y);
		}
		else
		{
			m_position-=D3DXVECTOR3(m_unit.x,0,m_unit.y);
			m_target-=D3DXVECTOR3(m_unit.x,0,m_unit.y);
		}
	}

	void Camera::WorldCenter(float worldW,float worldH)
	{
	}

	/*VOID Camera::GameCarmer()
	{
		static float cameraHeight = 10.0f;
		
		cameraHeight+=0.001f;
		if(cameraHeight>100.0f)
		{
			cameraHeight=-100.0f;
		}

		D3DXVECTOR3 m_position(  cameraHeight, 10.0f,  -10.0f );

		// the camera is targetted at the origin of the world
		D3DXVECTOR3 m_target(0.0f, 0.0f, 0.0f);

		// the worlds m_up vector
		D3DXVECTOR3 m_up(0.0f, 1.0f, 0.0f);

		D3DXMatrixLookAtLH(&m_ViewMatrix, &m_position, &m_target, &m_up);
		g_pd3dDevice->SetTransform(D3DTS_VIEW, &m_ViewMatrix);
	}*/

	D3DXMATRIX* Camera::GetViewMatrix()
	{
		D3DXMatrixLookAtLH(&m_ViewMatrix,&m_position,&m_target,&m_up);
		return &m_ViewMatrix;
	}
}